Hi,
first of all, on the typdef line, do something actually useful
hint :
Code:
typedef char* String
here's the stepwise evaluation for
Code:
void getString(charNode *start)
{
addElement(&start, "(1)Cat");
addElement(&start, "(2)Dog");
addElement(&start, "(3)Horse");
printList(start);
}
on the first call of add Element, *start is NULL (look at main() )
so according to your function, addElement returns start (by reference) by calling newNode
Code:
if (*start == NULL)
{
*start = temp;
}
** tips : instead of using strcpy, use strncpy ... strcpy doesn't have any check for buffer overflow.... to use strncpy :
Code:
strncpy(char *destination, char *source, bufferLength)
in your case :
strncpy(temp->petName, petName, 12);
so far, *start has a string "(1)Cat" according to
Code:
addElement(&start, "(1)Cat");
on the second call: (the part u actually asked )
Code:
addElement(&start, "(2)Dog");
before:
Code:
temp = newNode(petName); // making temp an element with new string in it
prev = NULL; // nowhere
loc = *start
/* loc has the same address as *start (ie harshly the same as saying
* int *i, a = 10;
* i = &a;
*/
"(1)Cat" -> NULL
^
loc
1st iteration :
Code:
prev = loc;
"(1)Cat" -> NULL
^
(prev & loc)
loc = loc->next // loc becomes NULL
"(1)Cat" -> NULL
^ ^
prev loc
the nullity of loc terminates the for loop and notice here how prev is actually used to store the last item in the list
then
temp->next = loc; // assigning the next of the temp to be NULL, since loc is null...
** tips : I don't personally think this is neccessary, since newNode has done this for you (Tested)
prev->next = temp; // simply appending the new element to the end of the old list
}
Hope dat helps